<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | 王勇程 <laughskydragon@qq.com>                         |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\common\model;

/**
 * 用户关注模型
 */
class UserFollow extends ModelBase
{
    // 表名

    
    // 自动时间戳
    protected $autoWriteTimestamp = true;
    
    // 时间字段
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    
    // 字段类型转换
    protected $type = [
        'id' => 'integer',
        'user_id' => 'integer',
        'product_id' => 'integer',
        'create_time' => 'integer',
        'update_time' => 'integer',
    ];

    /**
     * create_time获取器 - 时间戳转换为日期格式
     */
    public function getCreateTimeAttr($value)
    {
        return $value ? date('Y-m-d H:i:s', $value) : '';
    }

    /**
     * update_time获取器 - 时间戳转换为日期格式
     */
    public function getUpdateTimeAttr($value)
    {
        return $value ? date('Y-m-d H:i:s', $value) : '';
    }
    
    // 关联用户表
    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }
    
    /**
     * 关联商品表
     */
    public function product()
    {
        return $this->belongsTo(Product::class, 'product_id', 'id');
    }
    
    /**
     * 添加关注
     */
    public function addFollow($userId, $productId)
    {
        // 检查是否已关注
        $exists = $this->getInfo([
            'user_id' => $userId,
            'product_id' => $productId
        ]);
        
        if ($exists) {
            return ['code' => 0, 'msg' => '已关注该商品'];
        }
        
        // 使用事务确保数据一致性
        try {
            \think\facade\Db::transaction(function () use ($userId, $productId) {
                // 添加关注记录
                $result = $this->save([
                    'user_id' => $userId,
                    'product_id' => $productId
                ]);
                
                if (!$result) {
                    throw new \Exception('关注失败');
                }
                
                // 更新商品关注数 +1
                $productModel = new Product();
                $updateResult = $productModel->updateInfo(
                    ['id' => $productId], 
                    ['follow_count' => ['inc', 1]]
                );
                
                if (!$updateResult) {
                    throw new \Exception('更新关注数失败');
                }
            });
            
            return ['code' => 1, 'msg' => '关注成功'];
        } catch (\Exception $e) {
            return ['code' => 0, 'msg' => '关注失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 取消关注
     */
    public function removeFollow($userId, $productId)
    {
        // 检查是否已关注
        $exists = $this->getInfo([
            'user_id' => $userId,
            'product_id' => $productId
        ]);
        
        if (!$exists) {
            return ['code' => 0, 'msg' => '未关注该商品'];
        }
        
        // 使用事务确保数据一致性
        try {
            \think\facade\Db::transaction(function () use ($userId, $productId) {
                // 删除关注记录
                $result = $this->deleteInfo([
                    'user_id' => $userId,
                    'product_id' => $productId
                ]);
                
                if (!$result) {
                    throw new \Exception('取消关注失败');
                }
                
                // 更新商品关注数 -1
                $productModel = new Product();
                $updateResult = $productModel->updateInfo(
                    ['id' => $productId], 
                    ['follow_count' => ['dec', 1]]
                );
                
                if (!$updateResult) {
                    throw new \Exception('更新关注数失败');
                }
            });
            
            return ['code' => 1, 'msg' => '取消关注成功'];
        } catch (\Exception $e) {
            return ['code' => 0, 'msg' => '取消关注失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 检查是否已关注
     */
    public function isFollowed($userId, $productId)
    {
        $follow = $this->getInfo([
            'user_id' => $userId,
            'product_id' => $productId
        ]);
        
        return !empty($follow);
    }
    
    /**
     * 获取用户关注的商品列表
     */
    public function getUserFollowList($userId, $page = 1, $limit = 20)
    {
        $this->join = [
            ['product p', 'p.id = uf.product_id', 'INNER']
        ];
        
        return $this->alias('uf')->getList([
            'uf.user_id' => $userId,
            'p.status' => 1
        ], 'uf.*,p.name,p.brand,p.current_price,p.yesterday_price,p.image_url,p.category', 'uf.create_time desc', [
            'list_rows' => $limit,
            'page' => $page
        ]);
    }
    
    /**
     * 获取用户关注数量
     */
    public function getUserFollowCount($userId)
    {
        return $this->stat(['user_id' => $userId]);
    }
    
    /**
     * 获取商品关注数量
     */
    public function getProductFollowCount($productId)
    {
        return $this->stat(['product_id' => $productId]);
    }
    
    /**
     * 获取关注该商品的用户列表
     */
    public function getProductFollowers($productId, $page = 1, $limit = 20)
    {
        $this->join = [
            ['user u', 'u.id = uf.user_id', 'INNER']
        ];
        
        return $this->alias('uf')->getList([
            'uf.product_id' => $productId,
            'u.status' => 1
        ], 'uf.*,u.nickname,u.avatar_url', 'uf.create_time desc', [
            'list_rows' => $limit,
            'page' => $page
        ]);
    }
    
    /**
     * 批量检查关注状态
     */
    public function batchCheckFollow($userId, $productIds)
    {
        if (empty($productIds)) {
            return [];
        }
        
        $follows = $this->getList([
            'user_id' => $userId,
            ['product_id', 'in', $productIds]
        ], 'product_id');
        
        $followedIds = array_column($follows, 'product_id');
        
        $result = [];
        foreach ($productIds as $productId) {
            $result[$productId] = in_array($productId, $followedIds);
        }
        
        return $result;
    }
    
    /**
     * 清理用户所有关注
     */
    public function clearUserFollows($userId)
    {
        return $this->deleteInfo(['user_id' => $userId]);
    }
    
    /**
     * 获取价格变动金额
     */
    public function getChangeAmountAttr($value, $data)
    {
        $yesterdayPrice = $this->_getYesterdayPrice($data['id']);
        $marketPrice = floatval($data['market_price']);
        
        if ($yesterdayPrice > 0) {
            return $marketPrice - $yesterdayPrice;
        }
        return null; // 昨日价格为0时，变化金额为空
    }

    /**
     * 获取价格变动率（保留1位小数）
     */
    public function getChangeRateAttr($value, $data)
    {
        $yesterdayPrice = $this->_getYesterdayPrice($data['id']);
        $marketPrice = floatval($data['market_price']);

        if ($yesterdayPrice > 0) {
            $changeAmount = $marketPrice - $yesterdayPrice;
            $changeRate = ($changeAmount / $yesterdayPrice) * 100;
            return round($changeRate, 1); // 四舍五入保留1位小数
        }
        return null; // 昨日价格为0时，变化率为空
    }
    
    /**
     * 获取昨日价格
     * @param $value
     * @param $data
     * @return float|null
     */
    public function getYesterdayPriceAttr($value, $data)
    {
        return $this->_getYesterdayPrice($data['id']);
    }
    
    private $_cachedYesterdayPrice = [];

    /**
     * 获取指定商品的昨日价格 (私有方法)
     * @param int $productId 商品ID
     * @return float 昨日价格，如果不存在则返回0
     */
    private function _getYesterdayPrice(int $productId): float
    {
        // 检查是否已缓存
        if (isset($this->_cachedYesterdayPrice[$productId])) {
            return $this->_cachedYesterdayPrice[$productId];
        }

        // 确保 modelPriceHistory 已被初始化
        if (!isset($this->modelPriceHistory)) {
            $this->modelPriceHistory = new \app\common\model\PriceHistory();
        }

        $yesterdayDate = date('Y-m-d', strtotime('-1 day'));

        // 尝试获取昨日的价格记录
        $yesterdayPriceRecord = $this->modelPriceHistory->getInfo(
            [
                'product_id' => $productId,
                'price_date' => ['<=', $yesterdayDate]
            ],
            true,
            'price_date desc'
        );

        $price = $yesterdayPriceRecord ? floatval($yesterdayPriceRecord['price']) : floatval($this->getData('market_price'));

        // 缓存结果
        $this->_cachedYesterdayPrice[$productId] = $price;

        return $price;
    }
}